package br.com.LeitorLog.gui.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URL;


public final class SerializationUtils {
	
	private SerializationUtils() { }

	public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		ObjectInputStream ois = new ObjectInputStream(in);
		Object readObject = ois.readObject();
		ois.close();
		in.close();
		return readObject;
	}

	public static byte[] serialize(Object object) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(out);
		oos.writeObject(object);
		oos.flush();
		oos.close();
		return out.toByteArray();
	}
	
	public static InputStream createStream(String file) throws IOException {
		InputStream instream = FileUtils.class.getResourceAsStream(file);
		try {
			if (instream == null) {
				instream = new FileInputStream(new File(file));
			}
		} catch (Exception e1) {
			try {
				if (instream == null) {
					instream = new FileInputStream(new File(new File("."), file.substring(1)));
				}
			} catch (Exception e2) {
				URL url = SerializationUtils.class.getResource("/");
				File pastaClasses = null;
				try {
					pastaClasses = new File(url.toURI());
				} catch (URISyntaxException e) { e.printStackTrace(); }
				File arquivo = new File(pastaClasses, file.substring(1));
				instream = new FileInputStream(arquivo);
			}
		}
		return instream;
	}
	
	public static byte[] getBytesFromStream(InputStream stream) throws IOException {
		final ByteArrayOutputStream baos = new ByteArrayOutputStream();
		copy(stream, baos);
		return baos.toByteArray();
	}
	
	public static void copy(InputStream input, OutputStream output) throws IOException {
		byte[] buffer = new byte[1024];
		int read;
		while ((read = input.read(buffer)) > 0) {
			output.write(buffer, 0, (read > 0) ? read : 0);
		}
		output.flush();
		output.close();
		input.close();
	}
	
}
